/*
 * =====================================================================================
 *
 *       Filename:  test_queue.c
 *
 *    Description:  Read the file one line by one,
 *                  and store in a queue,
 *                  in another thread, it get the data from the queue.
 *
 *        Version:  1.0
 *        Created:  12/06/15 15:05:12
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andy (gk), andy_y_li@163.com
 *        Company:  RD
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include "queue.h"
#include "file.h"

typedef struct {
    FILE *fp;
    Queue  *qu;
} FdQueue;

void help(const char *app)
{
    fprintf(stderr, "Read the file one line by one,\
            \nand store in a queue,\
            \nin another thread, it get the data from the queue.\
            \nUsage: %s fileName\n", app);
}

void *get_content(void *arg) 
{
    Queue *qu = (Queue *)arg;
    char line[1024];
    //sleep(1);
    do {
        usleep(10000);
        int err = deItem(qu, line, 1024);
        if (err == 0) {
            break;
        }
        printf("%s",line);
    }while(1);
    return NULL;
}

void *store_content(void *arg)
{
    FdQueue *fq = (FdQueue *)arg;
    char line[1024];
    do {
        char *bytes = fgets(line, 1024, fq->fp);
        if (bytes == NULL) {
            break;
        }
        enItem(fq->qu, line);
    } while(1);

    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        help(argv[0]);
        return -1;
    }
    FILE *fp = fopen(argv[1],"r+");
    if (fp  == NULL) {
        fprintf(stderr, "open file(%s) error:%s\n",
                argv[1], strerror(errno));
        return -1;
    }

    Queue qu;
    createQueue(&qu);

    pthread_t tRequest;
    int err = pthread_create(&tRequest, NULL, get_content, &qu);
    if (err != 0) {
        fprintf(stderr, "pthread_create error: %s\n", strerror(errno));
        fclose(fp);
        return -1;
    }

    pthread_t tRead;
    FdQueue fq;
    fq.fp = fp;
    fq.qu = &qu;
    err = pthread_create(&tRead, NULL, store_content, (void *)&fq);
    if (err != 0) {
        fprintf(stderr, "pthread_create error: %s\n", strerror(errno));
        fclose(fp);
        return -1;
    }

    err = pthread_join(tRequest, NULL);
    if (err != 0) {
        fprintf(stderr, "pthread_join error: %s\n", strerror(errno));
        fclose(fp);
        return -1;
    }
    err = pthread_join(tRead, NULL);
    if (err != 0) {
        fprintf(stderr, "pthread_join error: %s\n", strerror(errno));
        fclose(fp);
        return -1;
    }

    fclose(fp);
    return 0;
}

